package coolq.yaozhenyong.custom;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.forte.qqrobot.BaseConfiguration;
import com.forte.qqrobot.beans.messages.msgget.GroupMemberIncrease;
import com.forte.qqrobot.beans.messages.result.GroupInfo;
import com.forte.qqrobot.sender.MsgSender;

import coolq.yaozhenyong.bean.GroupList;
import coolq.yaozhenyong.cocApi.custom.ClansClanTagCustom;
import coolq.yaozhenyong.cocApi.custom.ClansPlayersTagCustom;
import coolq.yaozhenyong.cocApi.entity.ClansClanTag.ClansClanTag;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.ClansPlayersTag;
import coolq.yaozhenyong.custom.entity.coc.Clans;
import coolq.yaozhenyong.custom.entity.ems.Ems;
import coolq.yaozhenyong.custom.entity.players.Clan;
import coolq.yaozhenyong.custom.entity.players.PlayersClans;
import coolq.yaozhenyong.custom.entity.toMM.ToMM;
import coolq.yaozhenyong.custom.entity.toTulin.ToTulin;
import coolq.yaozhenyong.service.GroupListService;

public class QqCqcustom {
	private static String tl[]= {
			"[CQ:sface,id=720934]不知道你在说什么。","我能力有限，无法回复你这句话。","可能我就是个文盲吧，尽然不知道你这句话什么意思","请换个我能理解话吧","可能我比较低级，无法回答你的话"
			,"你说的是火星文吗？","你换个人问问吧","我就是不想回答你","你干嘛问这么难回答的东西","无法回答，你向我的主人反馈吧\n主人QQ：936642284"
			,"你晓不晓得，我不是百度，不是什么都能回答你","面向百度问答，别问我了，我回答不了！","你是蔡徐坤吗？问我这种事情","你是很闲吗?问我这么难的东西！","你的问题就像我的脸[CQ:emoji,id=127773][CQ:emoji,id=127764][CQ:emoji,id=127763][CQ:emoji,id=127762][CQ:emoji,id=127770]"
			,"[CQ:sface,id=720934]你在说什么？","[CQ:face,id=32]？？？？？"
	};
	private static String nl[]= {
			"[CQ:sface,id=720934]不知道你在说什么。","[CQ:face,id=32]？？？？？","艾特我有什么事情吗？","请问你有什么需要？","我特别喜欢和你聊天了！","你就像cxk，emmm~~~"
			,"别艾特我了，我讨厌别人艾特我不说话","你需要表达什么，告诉我"
	};
	public static String e[][] = {
			{"顺丰","sf"},
			{"申通","sto"},{"圆通","yt"},{"韵达","yd"},{"天天","tt"},
			{"EMS","ems"},{"中通","zto"},{"汇通","ht"},{"全峰","qf"},
			{"德邦","db"},{"国通","gt"},{"如风达","rfd"},{"京东快递","jd"},{"京东","jd"},{"宅急送","zjs"},{"EMS国际","emsg"},
			{"Fedex国际","fedex"},{"邮政国内","yzgn"},{"UPS国际快递","ups"},{"中铁快运","ztky"},{"佳吉快运","jiaji"},{"速尔快递","suer"},
			{"信丰物流","xfwl"},{"优速快递","yousu"},{"中邮物流","zhongyou"},{"天地华宇","tdhy"},{"安信达快递","axd"},{"安信达","axd"},
			{"优速","yousu"},{"AAE全球专递","aae"},{"DHL","dhl"},{"DPEX国际快递","dpex"},{"D速物流","ds"},{"FEDEX国内快递","fedexcn"},
			{"OCS","ocs"},{"TNT","tnt"},{"东方快递","coe"},{"传喜物流","cxwl"},{"城市100","cs"},{"城市之星物流","cszx"},{"安捷快递","aj"},
			{"百福东方","bfdf"},{"程光快递","chengguang"},{"递四方快递","dsf"},{"长通物流","ctwl"},{"飞豹快递","feibao"},
			{"安能快递","ane66"},{"中通快运","ztoky"},{"远成物流","ycgky"},{"远成快运","ycky"},{"邮政快递","youzheng"},
			{"百世快运","bsky"},{"苏宁快递","suning"},{"苏宁","suning"},{"安能物流","anneng"},{"九曳","jiuye"}
	};
	/****
	 * 快递转义
	 * @param kuaidi 
	 */
	public static String ems(String kuaidi) {
		for (int i = 0; i < e.length; i++) {
			if(e[i][0].equals(kuaidi)) {
				return e[i][1];
			}
		}
		return null;
	}
	/***
	 * 发送查询快递的请求
	 * @param appkey 
	 * @param ems
	 * @param string 
	 * @return 
	 */
	public static Ems toEmsUrl(String appkey, String ems,String number, String phone) {
		//&senderPhone=&receiverPhone=
			
			try {
				String url = "http://v.juhe.cn/exp/index?com="+ems+"&no="+number+"&dtype=&key="+appkey+phone;
				Map<String, String> params = new HashMap<String, String>();//请求参数
	            params.put("com",ems);//需要查询的快递公司编号
	            params.put("no",number);//需要查询的订单号
	            params.put("key",appkey);//应用APPKEY(应用详细页查询)
	            params.put("dtype","json");//返回数据的格式,xml或json，默认json
				String sendGet = BackEndHttpRequest.sendEmsGet(url, params, "GET");
				ObjectMapper mapper = new ObjectMapper();
				Ems list;
				list = mapper.readValue(sendGet,new TypeReference<Ems>() { });
				return list;
			}catch (Exception e) {
				System.out.println(TimeUtils.getStringDate()+"快递请求失败"+ems+"快递号"+number);
			}
			
		return null;
			
	}
	/***
	 * 查询此人是否存在
	 * @param split
	 * @return
	 */
	public static Boolean goCocBd(String[] split) {
		switch (split[0]) {
		case "绑定村庄":
			try {
				ClansPlayersTag findAll = ClansPlayersTagCustom.findAll(split[1]);
				Boolean isCoc =  findAll.getDataisnull()!=null?findAll.getDataisnull():false;
				return isCoc;
			} catch (Exception e) {
			}
			return false;
		case "绑定部落":
			try {
				ClansClanTag findAll = ClansClanTagCustom.findAll(split[1]);
				Boolean isCoc =  findAll.getDataisnull()!=null?findAll.getDataisnull():false;
				return isCoc;
			} catch (Exception e) {
			}
			return false;
		default:
			return false;
		}
	}
	/****
	 * 发送查询部落接口
	 * @param substring
	 * @param string
	 */
	public static String goCocUrl(String substring, String string) {
		
		String msg="";
		if(substring.equals("查询部落")||substring.equals("部落")) {
			try {
				String url = "https://api.clashofstats.com/clans/"+string;
				String sendGet = BackEndHttpRequest.sendGet(url, "");
				ObjectMapper mapper = new ObjectMapper();
				Clans list = mapper.readValue(sendGet,new TypeReference<Clans>() { });
				String cocTpe = CocTpe(list.getType());
				if(list.getStatusCode()==null) {
					msg  = "[CQ:image,file="+list.getBadgeUrls().getSmall()+"]\n"+
							"[CQ:emoji,id=9876]"+list.getName()+"\n"
							+ "[CQ:emoji,id=127991]"+list.getTag()+"\n[CQ:emoji,id=127544]"
							+ cocTpe +"\n[CQ:emoji,id=128694]现已有"+list.getMembers()+"人\n"
							+ "[CQ:emoji,id=127751]奖杯："+list.getClanPoints()+"\n"
							+ "[CQ:emoji,id=127747]奖杯："+list.getClanVersusPoints()+"\n"
							+ "历史最佳:\n[CQ:emoji,id=127751]("+list.getBests().getClanPoints().getVal()+")[CQ:emoji,id=127747]("+list.getBests().getClanVersusPoints().getVal()+")";
					return msg;
				}
			} catch (Exception e) {
				System.err.println("发送查询部落"+string+"是发送失败！");
			}
		}
		if(substring.equals("查询村庄")||substring.equals("村庄")) {
			try {
				String url = "https://api.clashofstats.com/players/"+string;
				String sendGet = BackEndHttpRequest.sendGet(url, "");
				ObjectMapper mapper = new ObjectMapper();
				PlayersClans list = mapper.readValue(sendGet,new TypeReference<PlayersClans>() { });
				String cocTag ="";
				Clan clan = list.getClan();
				if(clan!=null) {
					cocTag = CocTag(clan.getRole());
				}else {
					cocTag = "未知";
				}
				String max = "";
				if(list.getTownHallLevel()!=null||list.getBuilderHallLevel()!=null) {
					if(list.getTownHallLevel()!=null&&list.getBuilderHallLevel()==null) {
						max ="[CQ:emoji,id=127751]"+list.getTownHallLevel()+"本\n";
					}
					if(list.getBuilderHallLevel()!=null&&list.getTownHallLevel()==null) {
						max =" [CQ:emoji,id=127747]"+list.getBuilderHallLevel()+"本\n";
					}else {
						max ="[CQ:emoji,id=127751]"+list.getTownHallLevel()+"本  [CQ:emoji,id=127747]"+list.getBuilderHallLevel()+"本\n";
					}
				}
				String legendTrophies = list.getLegendTrophies();
				if(legendTrophies!=null) {
					legendTrophies ="传奇[CQ:emoji,id=127941]" +legendTrophies;
				}else {
					legendTrophies="";
				}
				if(list.getStatusCode()==null) {
					msg = "[CQ:emoji,id=128481]"+list.getName()+"\n"
							+ "[CQ:emoji,id=127991]"+list.getTag()+"\n"
							+ "[CQ:emoji,id=9876]"+list.getClan().getName()+"\n"
							/*+ "职位："+cocTag+"\n"+*/
							+ max 
							+ "[CQ:emoji,id=128737]" + cocTag +"[CQ:face,id=144]"+list.getExpLevel()+"级\n"
							+ "[CQ:emoji,id=127942]"+list.getTrophies()+legendTrophies+"\n"
									+ "捐:"+list.getDonations()+"  收:"+list.getDonationsReceived()
									+ "\n\n历史最高：\n"
							+ "[CQ:emoji,id=127751][CQ:emoji,id=127942]"+list.getBestTrophies()+"[CQ:emoji,id=127747][CQ:emoji,id=127942]"+list.getBestVersusTrophies()+"\n";
					return msg;
				}
			} catch (Exception e) {
				System.err.println("发送查询村庄"+string+"是发送失败！");
			}
		}
		if(msg=="") {
			
		}
		msg = "抱歉哦，可能由于服务器延迟问题或者提供的#"+string+"编号错误，导致无法在规定时间查出您需要的信息，请稍等在进行查询哦！";
		return msg;
	}
	/****
	 * 发送图灵机器人
	 * @param appkey
	 * @param msg
	 */
	public static String goTulingUrl(String appkey, String msg) {
		//第一步还是接图灵的机器人b13c1038ddfb4d63a2e8fccde40ac784
		ObjectMapper mapper = new ObjectMapper();
		ToTulin list = new ToTulin();
		if(appkey!=null&&appkey.length()>0) {
			String tulinUrl ;
			try {
				tulinUrl = "http://www.tuling123.com/openapi/api?key="+appkey+"&info="+URLEncoder.encode(msg,"utf-8");
			} catch (UnsupportedEncodingException e) {
				tulinUrl = "http://www.tuling123.com/openapi/api?key="+appkey+"&info="+msg;
			}
			String sendPost = BackEndHttpRequest.sendPost(tulinUrl, "");
			try {
				list = mapper.readValue(sendPost,new TypeReference<ToTulin>() { });
				String url = list.getUrl();
				if(url!=null&&url.length()>0) {
			        String urltm = DlCustom.dl(url);
					list.setText(list.getText() + "\n"+urltm);
				}
			} catch (Exception e) {
			}
		}
		if(list==null||(!"100000".equals(list.getCode())&&!"200000".equals(list.getCode()))) {
			//第二款机器人http://drea.cc/mm.php
			String mmPost = "";
			/*try {
				mmPost = BackEndHttpRequest.sendPost("http://open.drea.cc/chat/get?keyWord="+URLEncoder.encode(msg,"utf-8")+"&userName=type=bbs", null);
			} catch (UnsupportedEncodingException e1) {
				mmPost = BackEndHttpRequest.sendPost("http://open.drea.cc/chat/get?keyWord="+msg+"&userName=type=bbs", null);
			}*/
			try {
				mmPost = BackEndHttpRequest.sendPost("http://api.qingyunke.com/api.php?key=free&appid=0&msg="+URLEncoder.encode(msg,"utf-8"), null);
			} catch (UnsupportedEncodingException e1) {
				mmPost ="";
			}
			ToMM tomm = new ToMM();
			try {
				tomm = mapper.readValue(mmPost,new TypeReference<ToMM>() { });
				//return tomm.getData().getReply();
				String content = tomm.getContent();
				if(content!=null&&!"未获取到相关信息".equals(content)) {
					content = content.replaceAll("\\{br\\}", "\n").replace("菲菲", "熙酱");
					//return tomm.getData().getReply()+"\n\nMM聊天机器人回复！";
					return content;
				}else {
					int max=nl.length - 1,min=0;
					int r = (int) (Math.random()*(max-min)+min); 
					return nl[r];
				}
			} catch (Exception e) {
				int max=tl.length - 1,min=0;
				int r = (int) (Math.random()*(max-min)+min); 
				return tl[r];
			}
		}else {
			return list.getText();
		}
	}
	
	/***
	 *编译
	 * @param tag
	 */
	private static String CocTag(String tag) {
		if(tag.equals("leader")) {
			return "首领";
		}else if(tag.equals("coLeader")) {
			return "副首领";
		}else if(tag.equals("admin")) {
			return "长老";
		}else {
			return "成员";
		}
		
	}
	private static String CocTpe(String type) {
		if(type.equals("inviteOnly")) {
			return "只有批准了才可加入";
		}else if(type.equals("open")) {
			return "任何人可加入";
		}else if(type.equals("closed")) {
			return "不可加入[CQ:emoji,id=128695]";
		}else {
			return type;
		}
	}



	public static String[][] a = {
			{"204301","恕在下能力有限，您查询的快递公司我无法查找。"},{"204302","您运单号好像不正确哦，我查不到信息。"},{"204303","我查不到信息哦！"},
			{"204304","查不到物流信息，我也知道您的包裹现在情况呀！"},{"204305","	因为寄件人或收件人手机尾号错误！我无法获取信息呀！"}
	};
	
	/***
	 * 
	 * @param resultcode 聚合错误返回级
	 * @param error_code 服务器错误返回级
	 * @return
	 */
	public static String returnUrl(String resultcode, String error_code) {
		for (int i = 0; i < a.length; i++) {
			if(error_code.equals(a[i][0])) {
				return a[i][1];
			}
		}
		return "你们群管理的接口已失效，快叫他重新申请Appkey接口哦!";
	}
	
	public static String[][] status_details = {
			{"PENDING","待查询"},{"NO_RECORD","无记录"},{"ERROR","查询异常"},{"IN_TRANSIT","运输中"},{"DELIVERING","派送中"},
			{"SIGNED","已签收"},{"REJECTED","拒签"},{"PROBLEM","疑难件"},{"INVALID","无效件"},{"TIMEOUT","超时件"},
			{"FAILED","派送失败"},{"SEND_BACK","退回"},{"TAKING","揽件"}
			};
	public static String status_detail(String status_detail) {
		for (int i = 0; i < status_details.length; i++) {
			if(status_details[i][0].equals(status_detail)) {
				return "你快递暂无最新物流，你快递状态为："+status_details[i][1]+"。";
			}
		}
		return "查询不到你快递的最新物流哦！";
	}
	
	/***
	 * 更新群信息
	 * @param msg
	 * @param msgsender
	 */
	public static void updateGroupList(GroupMemberIncrease msg, MsgSender msgsender) {
		try {
			GroupListService bean = SpringContextUtil.getBean(GroupListService.class);
			GroupList groupList = bean.query().eq("groupcode", msg.getGroup()).one();
			if(groupList!=null) {
				GroupInfo g = msgsender.GETTER.getGroupInfo(msg.getGroup());
				if(g!=null&&g.getName()!=null) {
					groupList.setName(g.getName());
					groupList.setLevel(g.getLevel()==null?"":g.getLevel()+"");
					groupList.setOpentype(g.getOpenType()==null?"":g.getOpenType()+"");
					String[] adminList = g.getAdminList();
					if(adminList!=null) {
						String admini = "";
						Boolean isgoto = false;
						Map<String, String> adminNickList = g.getAdminNickList();
						for (int i = 0; i < adminList.length; i++) {
							String string = adminList[i];
							String string2 = adminNickList.get(string);
							admini += string + "["+string2+"]"+",";
							if(string .equals(BaseConfiguration.getLocalQQCode())) {
								isgoto = true;
							}
						}
						groupList.setAdminlist(admini);
						if(isgoto) {
							groupList.setIsadmin("是管理");
						}else {
							groupList.setIsadmin(null);
						}
					}
					groupList.setBoard(g.getBoard());
					groupList.setComoleteintro(g.getCompleteIntro());
					groupList.setMaxnumber(g.getMaxMember()==null?"":g.getMaxMember()+"");
					groupList.setNumber(g.getMemberNum()==null?"":g.getMemberNum()+"");
					groupList.setOwnerqq(g.getOwnerQQ());
					groupList.setPos(g.getPos());
					bean.updateById(groupList);
				}
			}else {
				GroupInfo g = msgsender.GETTER.getGroupInfo(msg.getGroup());
				if(g!=null&&g.getName()!=null) {
					groupList = new GroupList();
					groupList.setGroupcode(msg.getGroup());
					groupList.setName(g.getName());
					groupList.setLevel(g.getLevel()==null?"":g.getLevel()+"");
					groupList.setOpentype(g.getOpenType()==null?"":g.getOpenType()+"");
					String[] adminList = g.getAdminList();
					if(adminList!=null) {
						String admini = "";
						Boolean isgoto = false;
						Map<String, String> adminNickList = g.getAdminNickList();
						for (int i = 0; i < adminList.length; i++) {
							String string = adminList[i];
							String string2 = adminNickList.get(string);
							admini += string + "["+string2+"]"+",";
							if(string .equals(BaseConfiguration.getLocalQQCode())) {
								isgoto = true;
							}
						}
						groupList.setAdminlist(admini);
						if(isgoto) {
							groupList.setIsadmin("是管理");
						}else {
							groupList.setIsadmin(null);
						}
					}
					groupList.setBoard(g.getBoard());
					groupList.setComoleteintro(g.getCompleteIntro());
					groupList.setMaxnumber(g.getMaxMember()==null?"":g.getMaxMember()+"");
					groupList.setNumber(g.getMemberNum()==null?"":g.getMemberNum()+"");
					groupList.setOwnerqq(g.getOwnerQQ());
					groupList.setPos(g.getPos());
					bean.save(groupList);
				}
			}
		} catch (Exception e) {
			System.out.println(msg.getGroup()+"群信息更新失败！");
		}
	}
	
	
	
	
}
